import logging
import requests as req
import time
logger = logging.getLogger()

class RequestURL():
    @staticmethod
    def _request_url_data(url, json_data=None, headers=None, retry_time=0, timeout=5, method='POST'):
        if retry_time < 0:
            raise Exception("retry time should be larger than 0")
        retry_time = retry_time + 1
        while retry_time:
            try:
                if method == 'POST':
                    # logger.debug("send url: [{url}] data: [{data}] header: {headers}".format(url=url, data=json_data, headers=headers))
                    rsp = req.post(url, json=json_data, timeout=timeout, headers=headers)
                elif method == "GET":
                    # logger.debug("send url: [{url}]  header: {headers}".format(url=url, headers=headers))
                    rsp = req.get(url, timeout=timeout, headers=headers)
                else:
                    rsp = None
                if rsp is None:
                    return None, False
                if 200 <= rsp.status_code < 300:
                    retry_time = 0
                    return rsp.text, True
                else:
                    retry_time = retry_time - 1
                    logger.error("sending url [%s] , respone code:%s msg:%s", url, rsp.status_code, rsp.text)
                    if retry_time > 0:
                        time.sleep(10)
            except:
                retry_time = retry_time - 1
                logger.error("sending url [%s] failed retry %s"%(url, retry_time))
                if retry_time > 0:
                    time.sleep(10)
        return None, False


